﻿' --- Copyright (c) notice NevoWeb ---
'  Copyright (c) 2008 SARL NevoWeb.  www.nevoweb.com. All rights are reserved.
' Author: D.C.Lee
' ------------------------------------------------------------------------
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' ------------------------------------------------------------------------
' This copyright notice may NOT be removed, obscured or modified without written consent from the author.
' --- End copyright notice --- 


Imports System
Imports System.Web
Imports System.Net
Imports System.IO
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Collections.Specialized

Namespace NEvoWeb.Modules.NB_Store.Gateway

    Public Class GatewayDIBS
        Inherits GatewayInterface

        ' ------------------------------------------------------------------------
        ' Step One: Display payment buttons on website checkout.
        ' This function simply send back the html needed to display a payment button(s) on the checkout page.
        ' NOTE:
        ' - The html in an imput field with a NAME attribute, which will be used later to check on postback
        '   to see if the button has been pressed.
        ' - All parameters for the gateway are assigned by reading the gateway xml settings (In this case "DIBS.gateway")
        ' ------------------------------------------------------------------------
        Public Overrides Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String) As String
            Dim strHTML As String = ""
            Dim objSCtrl As New SettingsController
            Dim objSInfo As NB_Store_SettingsInfo
            objSInfo = objSCtrl.GetSetting(PortalID, "DIBS.gateway", Lang)

            If Not objSInfo Is Nothing Then
                Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)
                Dim strParamXML As String = ""
                Dim xmlDoc As New Xml.XmlDataDocument
                Dim xmlNod As Xml.XmlNode
                Dim xmlNodList As Xml.XmlNodeList

                strParamXML = objSInfo.SettingValue

                xmlDoc.LoadXml(strParamXML)

                xmlNodList = xmlDoc.SelectNodes("root/buttons/*")

                For Each xmlNod In xmlNodList
                    If xmlNod.InnerText <> "" Then
                        strHTML &= "<INPUT TYPE=IMAGE NAME=" & xmlNod.InnerText & " BORDER=0 SRC=""" & xmlNod.Attributes(0).InnerText & """/>&nbsp;"
                    End If
                Next

                If xmlNodList.Count = 0 Then
                    strHTML &= "<INPUT TYPE=IMAGE NAME=DIBS BORDER=0 SRC=""" & setParams("ButtonImageURL") & """/>"
                End If


            Else
                Return "NO GATEWAY SETTINGS FOUND!! missing setting ""DIBS.gateway"""
            End If

            Return strHTML
        End Function

        ' ------------------------------------------------------------------------
        ' Step Two: Create the html to redirect the user, if the payment button is clicked.
        ' This function create the html needed to redirect the user to the banking gateway by using the "RemotePost.vb" in NB_Store.
        ' NOTE:
        ' - All parameters for the gateway are assigned by reading the gateway xml settings (In this case "DIBS.gateway")
        ' - On Checkout.ascx postback, the user will be redirected to "Remotepost.ascx", which will read the Html create
        '   in this function and write the html as a httpcontext response.
        ' ------------------------------------------------------------------------
        Public Overrides Sub SetBankRemotePost(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal Request As System.Web.HttpRequest)

            Dim RPost As New RemotePost

            'test if DIBS button has been clicked
            If GetBankClick(PortalID, Request) Then
                Dim objSCtrl As New SettingsController
                Dim objSInfo As NB_Store_SettingsInfo
                objSInfo = objSCtrl.GetSetting(PortalID, "DIBS.gateway", "None")
                Dim strParamXML As String = ""
                If Not objSInfo Is Nothing Then

                    strParamXML = objSInfo.SettingValue
                    Dim setParams As Hashtable = createSettingsTable(strParamXML)

                    Dim DIBSURL As String = setParams("paymentURL")

                    Dim objOCtrl As New OrderController
                    Dim oInfo As NB_Store_OrdersInfo = objOCtrl.GetOrder(OrderID)

                    If Not oInfo Is Nothing Then

                        'update stock tranction in progress
                        Dim objPCtrl As New ProductController
                        objPCtrl.UpdateModelQtyTrans(oInfo.OrderID)

                        'set order status to redirect to bank
                        oInfo.OrderStatusID = 20
                        objOCtrl.UpdateObjOrder(oInfo)

                        RPost = New RemotePost

                        RPost.Add("amount", Replace(Replace(Format(oInfo.Total, "0.00"), ".", ""), ",", ""))
                        RPost.Add("orderid", oInfo.OrderID.ToString)

                        If Not oInfo Is Nothing Then
                            Dim xmlDoc As New Xml.XmlDataDocument
                            Dim xmlNod As Xml.XmlNode
                            Dim xmlNodList As Xml.XmlNodeList
                            Dim objTR As New TokenStoreReplace(oInfo, GetCurrentCulture)
                            Dim strNodText As String = ""
                            Dim objCart As NB_Store_CartInfo
                            objCart = CurrentCart.GetCurrentCart(PortalID)

                            If Not objCart Is Nothing Then
                                strParamXML = Replace(strParamXML, "[CARTID]", objCart.CartID)
                            End If

                            strParamXML = Replace(strParamXML, "[ORDERID]", oInfo.OrderID.ToString)
                            strParamXML = Replace(strParamXML, "[LANG]", GetCurrentCulture.Substring(0, 2))
                            strParamXML = objTR.DoTokenReplace(strParamXML)

                            xmlDoc.LoadXml(strParamXML)

                            xmlNodList = xmlDoc.SelectNodes("root/params/*")

                            For Each xmlNod In xmlNodList
                                If xmlNod.InnerText <> "" Then
                                    strNodText = xmlNod.InnerText
                                    RPost.Add(xmlNod.Name, strNodText)
                                End If
                            Next

                            If GetImageKeyValue(PortalID, Request) <> "DIBS" Then
                                RPost.Add("paytype", GetImageKeyValue(PortalID, Request))
                            End If

                        End If

                        RPost.Url = DIBSURL

                        Dim objCInfo As NB_Store_CartInfo = CurrentCart.GetCurrentCart(PortalID)
                        'Save the report html into the cart, the user will be redirect to this 
                        objSInfo = objSCtrl.GetSetting(PortalID, "gateway.loadimage", "None")
                        objCInfo.BankHtmlRedirect = RPost.GetPostHtml(objSInfo.SettingValue)
                        CurrentCart.Save(objCInfo)

                        'UpdateLog("DIBS = " & objCInfo.BankHtmlRedirect)

                    End If
                End If
            End If
        End Sub

        ' ------------------------------------------------------------------------
        ' Step Three: Auto Response from banking gateway.
        ' If the banking gateway supports Automatic response (A url is send to the store just after the users make the payment, 
        '  but before they click to return to the store) then this function deals with what needs to be done in NB_Store.
        ' NOTE:
        ' - All required values are passed back from DIBS in the URL.
        ' ------------------------------------------------------------------------
        Public Overrides Sub AutoResponse(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest)
            Dim objOCtrl As New OrderController
            Dim objPCtrl As New ProductController
            Dim objOInfo As NB_Store_OrdersInfo
            Dim ordID As Integer = -1
            Dim cartID As String = ""
            Dim lang As String = ""

            UpdateLog("AUTO FORM:  " & Request.Form.ToString)
            UpdateLog("AUTO URL:  " & Request.Url.ToString)

            If Not Request.QueryString("language") Is Nothing Then
                lang = Request.QueryString("language")
            End If

            If Not Request.QueryString("cartid") Is Nothing Then
                cartID = Request.QueryString("cartid")
            End If

            If Not Request.QueryString("ordID") Is Nothing Then
                ordID = Request.QueryString("ordID")
            End If

            objOInfo = objOCtrl.GetOrder(ordID)

            If Not objOInfo Is Nothing Then


                'clear cart parameters 
                Dim objCCtrl As New CartController
                Dim objCInfo As NB_Store_CartInfo = objCCtrl.GetCart(cartID)
                If Not objCInfo Is Nothing Then
                    objCInfo.BankTransID = -1
                    objCInfo.BankHtmlRedirect = ""
                    objCCtrl.UpdateObjCart(objCInfo)
                End If

                'check that the order is valid. (Not yet been processed)
                If Not objOInfo.OrderIsPlaced And objOInfo.OrderStatusID <> 30 Then
                    ' DIBS system only calls AutoResponse if transaction is successful.
                    'remove qty in trans
                    objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                    'set order status to Payed
                    objOInfo.OrderStatusID = 40
                    Dim UsrID As Integer = objOInfo.UserID
                    If UsrID = -1 Then UsrID = 0
                    objOInfo.OrderNumber = Format(PortalID, "00") & "-" & UsrID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                    objOInfo.OrderIsPlaced = True
                    If Not Request.Form("transact") Is Nothing Then
                        objOInfo.BankAuthCode = Request.Form("transact")
                    End If
                    objOCtrl.UpdateObjOrder(objOInfo)

                    'update in email
                    SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentOK.email", lang)
                    SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentOK.email")

                End If
            End If
        End Sub

        ' ------------------------------------------------------------------------
        ' Step Four: User returned from banking gateway.
        ' Once the user has made a payment and clicked to return to the store, then this function deals with displaying
        '  the return message, either success of failed.
        ' It this case has the functionaity to process the order on the NB_Store side has been added, in case the AutoResponse (IPN in DIBS)
        '  has not been setup.
        ' NOTE:
        ' - All required values are passed back from DIBS in the URL. (This means we need to check if the user is authorised to view the order.) 
        ' - We need to test if the autoreponse has already processed the order, by using the order status and OrderIsPlaced properties.
        ' ------------------------------------------------------------------------
        Public Overrides Function GetCompletedHtml(ByVal PortalID As Integer, ByVal UserID As Integer, ByVal Request As System.Web.HttpRequest) As String
            Dim objSCtrl As New SettingsController
            Dim objOCtrl As New OrderController
            Dim objPCtrl As New ProductController
            Dim objOInfo As NB_Store_OrdersInfo
            Dim objSInfo As NB_Store_SettingsTextInfo
            Dim ordID As Integer = -1
            Dim rtnMsg As String = ""
            Dim cartID As String = ""
            Dim lang As String = ""

            'UpdateLog("RETURN FORM:  " & Request.Form.ToString)
            'UpdateLog("RETURN URL:  " & Request.Url.ToString)

            If Not Request.QueryString("language") Is Nothing Then
                lang = Request.QueryString("language")
            End If

            If Not Request.QueryString("cartid") Is Nothing Then
                cartID = Request.QueryString("cartid")
            End If

            If Not Request.QueryString("ordID") Is Nothing Then
                ordID = Request.QueryString("ordID")
            End If

            'set rtnMsg to security error message
            objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentSECURITY.text", GetCurrentCulture)
            rtnMsg = objSInfo.SettingText
            If IsNumeric(ordID) Then
                objOInfo = objOCtrl.GetOrder(ordID)
                If Not objOInfo Is Nothing Then
                    If objOInfo.UserID = UserID Then

                        'clear cart parameters 
                        Dim objCCtrl As New CartController
                        Dim objCInfo As NB_Store_CartInfo = objCCtrl.GetCart(cartID)
                        If Not objCInfo Is Nothing Then
                            objCInfo.BankTransID = -1
                            objCInfo.BankHtmlRedirect = ""
                            objCCtrl.UpdateObjCart(objCInfo)
                        End If

                        Select Case UCase(Request.QueryString("DIBSAction"))
                            Case "CANCEL"
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced Then
                                    'check if order has already been cancelled
                                    If Not objOInfo.OrderStatusID = 30 Then
                                        'remove qty in trans
                                        objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                                        'set order status to cancelled
                                        objOInfo.OrderStatusID = 30
                                        If Not Request.Form("transact") Is Nothing Then
                                            objOInfo.BankAuthCode = Request.Form("transact")
                                        End If
                                        objOCtrl.UpdateObjOrder(objOInfo)
                                    End If
                                    'set Cancel order message
                                    objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentFAIL.text", GetCurrentCulture)
                                    rtnMsg = objSInfo.SettingText

                                End If
                            Case "RETURN"
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced And Not objOInfo.OrderStatusID = 30 Then
                                    'This update code should never run as an accepted order should be updated by the AutoResponse call.
                                    ' but is placed here incase the auto response fails for some reason.

                                    'remove qty in trans
                                    objPCtrl.UpdateStockLevel(objOInfo.OrderID)
                                    'set order status to Payed
                                    objOInfo.OrderStatusID = 45
                                    objOInfo.OrderNumber = Format(PortalID, "00") & "-" & UserID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                                    objOInfo.OrderIsPlaced = True
                                    objOCtrl.UpdateObjOrder(objOInfo)
                                    SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentunverified.email", lang)
                                    SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentunverified.email")
                                End If
                                'set completed order message
                                objSInfo = objSCtrl.GetSettingsText(PortalID, "paymentOK.text", GetCurrentCulture)
                                rtnMsg = objSInfo.SettingText

                            Case Else
                                ' break
                        End Select

                        'Do Token Replacement
                        Dim objTR As New TokenStoreReplace(objOInfo, GetMerchantCulture(PortalID))
                        rtnMsg = objTR.DoTokenReplace(rtnMsg)
                    End If
                End If
            End If
            Return rtnMsg
        End Function

        Public Overrides Function GetBankClick(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest) As Boolean
            'test if DIBS button has been clicked
            If GetImageKeyValue(PortalID, Request) = "" Then
                Return False
            Else
                Return True
            End If
        End Function

        Public Function createSettingsTable(ByVal SettingsParams As String) As Hashtable
            Return ParseGateway(SettingsParams)
        End Function

        Private Function GetImageKeyValue(ByVal Portalid As Integer, ByVal Request As System.Web.HttpRequest) As String
            Dim ImageKeyX As String = ""
            Dim strParamXML As String = ""
            Dim xmlDoc As New Xml.XmlDataDocument
            Dim xmlNod As Xml.XmlNode
            Dim xmlNodList As Xml.XmlNodeList
            Dim hashImages As New Hashtable

            strParamXML = GetStoreSetting(Portalid, "DIBS.gateway", GetCurrentCulture)

            xmlDoc.LoadXml(strParamXML)

            xmlNodList = xmlDoc.SelectNodes("root/buttons/*")

            For Each xmlNod In xmlNodList
                If xmlNod.InnerText <> "" Then
                    hashImages.Add(xmlNod.InnerText.ToUpper, xmlNod.InnerText.ToUpper)
                End If
            Next
            hashImages.Add("DIBS", "DIBS")


            Dim lp As Integer
            Dim c As Integer = 0
            For lp = 0 To Request.Form.Count - 1
                If Request.Form.Keys(lp).ToUpper.EndsWith(".X") Then
                    If hashImages.Contains(Replace(Request.Form.Keys(lp).ToUpper, ".X", "")) Then
                        ImageKeyX = Replace(Request.Form.Keys(lp).ToUpper, ".X", "")
                        c = c + 1
                    End If
                End If
            Next

            If c = 1 Then
                Return ImageKeyX
            Else
                Return ""
            End If
        End Function

    End Class



End Namespace

